package cn.ubeta.ar;

import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Toast;

import cn.ubeta.ar.camera.CameraInterface;
import cn.ubeta.ar.camera.CameraSurfaceView;
import cn.ubeta.ar.jni.JniUtils;
import cn.ubeta.ar.utils.DisplayUtil;
import cn.ubeta.ar.utils.EventUtil;
import cn.ubeta.ar.utils.FileUtils;
import cn.ubeta.ar.utils.PermissionUtils;

public class MainActivity extends AppCompatActivity implements Camera.PreviewCallback {

    CameraSurfaceView mCameraSurfaceView;
    private MainHandler mMainHandler = null;
    private int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;

    BoundView mBoundView;
    private Camera.Size mPreviewSize;
    private float mPreviewZoom;
    private int mScreenHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //requestWindowFeature(FEATURE_NO_TITLE);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        mCameraSurfaceView = (CameraSurfaceView) findViewById(R.id.cam_surface_view);
        mBoundView = (BoundView) findViewById(R.id.bound_view);

        // 检测相机权限
        if (PermissionUtils.hasCameraPermission(this)) {
            initTrack();
        } else {
            PermissionUtils.reqCameraPermission(this);
        }
    }

    /**
     * 初始化检测
     */
    private void initTrack() {
        ViewGroup.LayoutParams params = mCameraSurfaceView.getLayoutParams();
        params.width = DisplayUtil.getScreenWidth(this);
        params.height = DisplayUtil.getScreenHeight(this);
        mCameraSurfaceView.setLayoutParams(params);

        Bitmap bmp = FileUtils.readBitmapFromAssets(this, "logo.png");
        if (bmp == null) {
            Toast.makeText(this, "初始化失败！", Toast.LENGTH_LONG).show();
            return;
        }
        JniUtils.arInit(FileUtils.bmp2Bytes(bmp), bmp.getWidth(), bmp.getHeight());

        mMainHandler = new MainHandler();
        mMainHandler.sendEmptyMessageDelayed(EventUtil.TURN_TO_FRONT_CAMERA, 500);
    }

    private class MainHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EventUtil.CAMERA_HAS_STARTED_PREVIEW:
                    startTrack();
                    break;
                case EventUtil.TURN_TO_FRONT_CAMERA:
                    CameraInterface.getInstance().doStopCamera();
                    CameraInterface.getInstance().doOpenCamera(null, mCameraId);
                    CameraInterface.getInstance().doStartPreview(MainActivity.this, mCameraSurfaceView.getSurfaceHolder());

                    mPreviewSize = CameraInterface.getInstance().getCameraDevice().getParameters().getPreviewSize();
                    mPreviewZoom = (float)DisplayUtil.getScreenWidth(MainActivity.this) / (float)mPreviewSize.height;
                    Log.e("mPreviewZoom", "mPreviewZoom " + mPreviewZoom);
                    
                    mScreenHeight = DisplayUtil.getScreenWidth(MainActivity.this);

                    mMainHandler.sendEmptyMessageDelayed(EventUtil.CAMERA_HAS_STARTED_PREVIEW, 500);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }

    Paint paint;

    /**
     * 开始追踪
     */
    private void startTrack() {
        Log.e("startTrack", "startTrack");

        paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth((float) 5.0);

        CameraInterface.getInstance().getCameraDevice().setPreviewCallback(this);
    }

    /**
     * 权限回调
     * @param requestCode
     * @param permissions
     * @param results
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] results) {
        if (requestCode == PermissionUtils.REQ_CODE_PERM_CAMERA) {
            if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) {
                initTrack();
            }
        }
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        long startTime = System.currentTimeMillis();
        if (data == null) {
            Log.e("onPreviewFrame", "data null");
            return;
        }

        int[] bound = JniUtils.arTracking(data, mPreviewSize.width, mPreviewSize.height);
        if (bound == null || bound.length != 8) {
            mBoundView.setBound(null);
        } else {
            float[] fBound = {
                    mScreenHeight - bound[0] * mPreviewZoom, bound[1] * mPreviewZoom, mScreenHeight - bound[2] * mPreviewZoom, bound[3] * mPreviewZoom,
                    mScreenHeight - bound[2] * mPreviewZoom, bound[3] * mPreviewZoom, mScreenHeight - bound[4] * mPreviewZoom, bound[5] * mPreviewZoom,
                    mScreenHeight - bound[4] * mPreviewZoom, bound[5] * mPreviewZoom, mScreenHeight - bound[6] * mPreviewZoom, bound[7] * mPreviewZoom,
                    mScreenHeight - bound[6] * mPreviewZoom, bound[7] * mPreviewZoom, mScreenHeight - bound[0] * mPreviewZoom, bound[0] * mPreviewZoom};
            mBoundView.setBound(fBound);
        }

        //Log.e("onPreviewFrame", "traking time " + (System.currentTimeMillis() - startTime));
    }
}
